import React, {Component} from 'react'
import styles from './study.less'
import Video from "../../components/Video/video"
import Tree from "../../components/Tree/Tree"
import { message } from 'antd'
import { connect } from 'dva'
import { GET_COURSE_DETAIL } from "../../actions/course"
import { getVideoUrl } from '../../services/course'

@connect(({ course }) => ({
  course
}))
class Study extends Component {
  constructor(props) {
    super(props);
    this.state = {
      collapsed: false,
      url: ''
    }
  }

  componentDidMount() {
    const {dispatch, match: {params: {id}}} = this.props
    dispatch(GET_COURSE_DETAIL(id))
  }

  renderVideos(videos) {
    videos.forEach(item => {
      item.level = 'level1'
    })
    const node = {
      child: [
        ...videos
      ]
    }
    return <Tree treeList={node} clickTree={this.clickTree.bind(this)}/>
  }

  async clickTree(id) {
    let res = await getVideoUrl(id)
    if (res.data.code == 0) {
      this.setState({
        url: res.data.data
      })
    } else {
      this.setState({
        url: ''
      })
      message.error(res.data.msg)
    }
  }

  render() {
    const {url} = this.state
    const {course: { detail }} = this.props
    const { title, videos = [] } = detail
    return (
      <div className={styles.studyContainer}>
         <div className={styles.header}>
           <span className={styles.headerText}>目录</span>
           <span className={styles.courseName}>{title}</span>
         </div>
         <div className={styles.catalogue}>
           {this.renderVideos(videos)}
         </div>
        <div className={styles.playContainer}>
          <Video videos={videos} url={url}/>
        </div>
      </div>
    );
  }
}

export default Study;